import numpy as np

def show(x, k):
    print("第{}次迭代：".format(k))
    for i in range(len(x)):
        print(x[i][0])
    print()

def jaco(A, b, t, e):
    # L = A.tril(A)
    # U = A.tril(A)
    m = A.shape[0]  # 先计算出所需要的参数
    n = A.shape[1]
    D = np.diag(np.diag(A))
    I = np.eye(n)
    # x = np.ones((m,1))  # 注意需要创建列向量
    x = np.arange(m).reshape((-1,1))
    D1 = np.linalg.inv(D)
    BJ = I - np.matmul(D1,A)
    FJ = np.matmul(D1,b)
    count = 0
    pre = 1
    while count < t and pre > e:
        x1 = np.matmul(BJ,x) + FJ  # 获取迭代结果
        pre = 0
        for i in range(len(x1)):  # 计算精度
            pre += abs(x1[i][0] - x[i][0])  # 注意这里要加绝对值
        pre /= len(x1)
        
        # print(pre)
        x = x1  # 更新迭代结果
        count += 1
        show(x1, count)
    return x


if __name__ == '__main__':
    # A = np.array([[1., 1, 1],[1, -1, 1], [2, 1, 1]])  # attention here decimal point 
    # B = np.array([3., 1, 4]).reshape((-1,1))
    # A = np.array([[10.,-1,-2],[-1,10,-2],[-1,-1,5]])
    # B = np.array([[72.],[83],[42]]).reshape((-1,1))
    # A = np.array([[12., -3, 3],[-18, 3, -1], [1, 1, 1]])  # attention here decimal point 
    # B = np.array([15., -15, 6]).reshape((-1,1))
    A = np.array([[1., 2, -2],[1, 1, 1], [2, 2, 1]])  # attention here decimal point 
    B = np.array([1., 3, 5]).reshape((-1,1))
    x = jaco(A,B,100,1e-4)  # 最多迭代100次，精度为1e-6
    print('最终结果：')
    print(x)